package com.hw.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetSocketAddress;
import java.util.Scanner;

public class NettyClient {
	
	private String host;
	private int port;
	
	public NettyClient(String host, int port) {
		this.host = host;
		this.port = port;
	}
	
	public void start() throws InterruptedException {
		EventLoopGroup group=new NioEventLoopGroup();
		
		try {
			Bootstrap b=new Bootstrap();
			b.group(group)
			.remoteAddress(new InetSocketAddress(host, port))
			.channel(NioSocketChannel.class)
			.handler(new ChannelInitializer<SocketChannel>() {

				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
					ch.pipeline().addLast("Client Handler",new NettyClientHandler());
				}
			});
			
			ChannelFuture future=b.connect().sync();
			
			future.channel().closeFuture().sync();
			
		}finally {
			group.shutdownGracefully().sync();
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		
//		String host="127.0.0.1";
//		int port=9090;
		
//		if (args.length!=1) {
//			System.err.println(EchoClient.class.getSimpleName()+":请输入地址和端口号");
//			return;
//		}
		
		System.out.println(NettyClient.class.getSimpleName());
		@SuppressWarnings("resource")
		Scanner scanner=new Scanner(System.in);
		System.err.println("请输入ip：");
		String host=scanner.nextLine();
		System.err.println("请输入端口：");
		int port=scanner.nextInt();
		
		new NettyClient(host, port).start();
		
	}

}
